# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
import csv
from typing import Any, Dict, List, Text

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

data_list = []


# Title	Name	Review Date	Airline	Verified	Reviews	Type of Traveller	Month Flown	Route	Class	Seat Comfort	Staff Service	Food & Beverages	Inflight Entertainment	Value For Money	Overall Rating	Recommended	from				to	via


def load_csv():
    print("action_query_flight init -load_csv")
    with open('csv/min-arilines.csv') as f:
        read_data = csv.reader(f)
        is_first_row = True
        for row in read_data:
            if (is_first_row):
                print("skip first row")
                is_first_row = False
                continue
            item_from = row[17]
            item_to = row[21]
            print(f"item_from: {item_from}, item_to: {item_to}")
            data_list.append(row)


load_csv()


def find_match_item(departure, destination, ):
    match_item = None
    for item in data_list:
        item_from = item[17]
        item_to = item[21]
        item_class = item[9]
        if item_from.strip().lower() == departure.strip().lower() and item_to.strip().lower() == destination.strip().lower():
            match_item = item
            print(f"find match item,{item}")
            break

    return match_item


class ActionQueryFlight(Action):

    def name(self) -> Text:
        return "action_query_flight"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        print("do action  action_query_flight")
        # extra slot
        departure = tracker.get_slot("departure")
        destination = tracker.get_slot("destination")

        print(f"action extra,departure={departure},destination={destination}")

        match_item_list = find_match_item(departure, destination)

        if match_item_list:
            match_item_class_enum = set([])
            for match_item in match_item_list:
                item_class = match_item[9]
                match_item_class_enum.add(item_class.lower())

            match_item_class_enum_join_str = ""
            for e in match_item_class_enum:
                match_item_class_enum_join_str += f"{e},"
            msg = f"Which class do you need? {match_item_class_enum_join_str}?"
            dispatcher.utter_message(msg)
        else:
            msg = f"I'm sorry, we don't have flight information from {departure} to {destination}. Do you have any other flight needs?"
            dispatcher.utter_message(msg)

        return []
        # return [SlotSet("has_match_flight", has_match_flight)]


if __name__ == '__main__':
    load_csv()
    find_match_item('Jakarta', 'Singapore')
